import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { Logger } from 'common/lib/utils/log4js';
import * as Chalk from 'chalk';

//引入
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { HttpExceptionFilter } from 'common/lib/filters/http-exception.filter';

//引入日志中间件
import { logger } from 'common/lib/middleware/logger/logger.middleware';

import { TransformInterceptor } from 'common/lib/interceptor/transform/transform.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const config = app.get(ConfigService);
  const port = config.get('business.port');
  const tport = config.get('business.tport');

  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.TCP,
    options: {
      port: tport,
    },
  });

  app.setGlobalPrefix('business');

  // 监听所有的请求路由，并打印日志
  app.use(logger);

  //全局使用拦截器
  app.useGlobalInterceptors(new TransformInterceptor());

  // 过滤处理http异常
  app.useGlobalFilters(new HttpExceptionFilter());

  //配置swagger
  const swaggerOptions = new DocumentBuilder()
    .setTitle('business-api-文档') //文档标题
    .setDescription('business-api-说明') //文档描述
    .setVersion('1.0') //文档版本
    .addBasicAuth() //鉴权，可以输入token
    .build(); //创建

  //创建swagger
  const document = SwaggerModule.createDocument(app, swaggerOptions);
  //启动swagger
  SwaggerModule.setup('business', app, document); // 访问路径为 localhost:port/business

  app.enableCors(); //开启跨域访问

  await app.startAllMicroservices();
  await app.listen(port);
  Logger.log(
    Chalk.green(`business 服务启动成功 `),
    '\n',
    Chalk.yellow(`http://localhost:${port}/`),
  );
}
bootstrap();
